<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/5/12
 * Time: 19:15
 */

namespace app\api\controller;

use app\api\model\SysSite as SysSiteModel;
use app\api\model\Member as MemberModel;
use app\api\model\ZhChat as ZhChatModel;
use app\api\model\ZhChatLog as ZhChatLogModel;
use think\facade\Db;

class ZhChat extends Common
{
    // 获取会话列表
    public function index()
    {
        $wxapp_id = $this->request->get('wxapp_id');
        $uId      = $this->request->get('uid');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if (!$user) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }
        /*
        $map1 = [
            ['wxapp_id', '=', $wxapp_id],
            ['status', '=', 1],
            ['u_id', '=', $uId],
        ];*/
        $map2 = [
            ['wxapp_id', '=', $wxapp_id],
            ['status', '=', 1],
            ['u_id', '>', 0],
            ['s_id', '=', $uId]
        ];
        $data = ZhChatModel::where($map2)->select()->toArray();
        foreach ($data as &$v) {
            if ($v['u_id'] != $uId) {
                $oId = $v['u_id'];
            } else {
                $oId = $v['s_id'];
            }
            $memberData      = MemberModel::where([
                'wxapp_id' => $wxapp_id,
                'uid'      => $oId
            ])->field('nickname,avatar,uid')
                ->find();
            $v['chat_user']  = $memberData;
            $v['unread_num'] = ZhChatLogModel::where([
                'wxapp_id' => $wxapp_id,
                'chat_id'  => $v['id'],
                'u_id'     => $oId,
                'is_read'  => 0
            ])->count('id');
            $lastInfo        = ZhChatLogModel::where([
                'wxapp_id' => $wxapp_id,
                'chat_id'  => $v['id']
            ])->order('id desc')
                ->field('type,content,record_time')
                ->find();

            if ($lastInfo && $lastInfo['type'] == 'img') {
                $v['last_info'] = '[图片]';

            } elseif ($lastInfo && $lastInfo['type'] == 'voice') {
                $v['last_info'] = '[语音]';
            } elseif ($lastInfo && $lastInfo['type'] == 'text') {
                $v['last_info'] = $lastInfo['content'];
            } else {
                $v['last_info'] = '';
            }
            $v['record_time'] = $lastInfo['record_time'] ?: '';
        }
        unset($v);
        return $this->ajaxReturn($this->successCode, '成功', $data);
    }

    // 获取聊天记录
    function getChatRecord()
    {
        $wxapp_id = $this->request->get('wxapp_id');
        $uId      = $this->request->uid;
        $sId      = $this->request->get('s_id', '', 'serach_in');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if (!$user) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }

        $SUser = MemberModel::where(['uid' => $sId, 'wxapp_id' => $wxapp_id])->find();
        if (!$SUser) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }

        $map1     = [
            ['wxapp_id', '=', $wxapp_id],
            ['u_id', '=', $uId],
            ['s_id', '=', $sId]
        ];
        $map2     = [
            ['wxapp_id', '=', $wxapp_id],
            ['u_id', '=', $sId],
            ['s_id', '=', $uId]
        ];
        $findData = ZhChatModel::whereOr([$map1, $map2])->find();
//        if(!$findData){
//            $res = [];
//            return $this->ajaxReturn($this->successCode,'返回成功',htmlOutList($res));
//        }
        $limit   = $this->request->get('limit', 20, 'intval');
        $page    = $this->request->get('page', 1, 'intval');
        $field   = 'a.*,b.uid,b.nickname,b.avatar';
        $orderby = 'a.id desc';

        $where = [
            'a.wxapp_id' => $wxapp_id,
            'a.chat_id'  => $findData['id'] ?: 0
        ];
        ZhChatLogModel::where(['wxapp_id' => $wxapp_id, 'chat_id' => $findData['id'], 'is_read' => 0, 'u_id' => $sId])->update(['is_read' => 1]);
        $chatLogData         = ZhChatLogModel::alias('a')
            ->join('member b ', 'b.uid= a.u_id')
            ->where($where)
            ->field($field)
            ->order($orderby)
            ->paginate(['list_rows' => $limit, 'page' => $page])
            ->toArray();
        $chatLogData['data'] = array_reverse($chatLogData['data']);
        foreach ($chatLogData['data'] as &$v) {
            $v = [
                'type' => 'user',
                'msg'  => [
                    'id'       => $v['id'],
                    'type'     => $v['type'],
                    'time'     => $v['record_time'],
                    'userinfo' => [
                        'uid'      => $v['uid'],
                        'username' => $v['nickname'],
                        'face'     => $v['avatar']
                    ],
                    'content'  => $v['type'] == 'text' ? [$v['type'] => $v['content']] : json_decode($v['content'])
                ]
            ];
        }


//        unset($v);
        $res['sdata'] = $SUser;
        $res['data']  = $chatLogData;
        //dd($res);die;//htmlOutList($res)
        return $this->ajaxReturn($this->successCode, '返回成功', $res);
    }

    function count()
    {
        $wxapp_id = $this->request->get('wxapp_id');
        $uId      = $this->request->get('uid');

        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }

        if(intval($uId)==0){
            return $this->ajaxReturn($this->errorCode, '缺少uid参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        /*
        $map1   = [
            ['gc_zh_chat.wxapp_id', '=', $wxapp_id],
            ['gc_zh_chat.status', '=', 1],
            ['gc_zh_chat.u_id', '=', $uId],
        ];
        $map2   = [
            ['gc_zh_chat.wxapp_id', '=', $wxapp_id],
            ['gc_zh_chat.status', '=', 1],
            ['gc_zh_chat.s_id', '=', $uId]
        ];
        $zhChat = new ZhChatModel();
        $ZhChatModel=new ZhChatModel();
       // $zhChat->whereOr([$map1, $map2]);
*/

        /*
        $sql= "SELECT COUNT(gc_zh_chat.id)  as num FROM     gc_zh_chat
              LEFT JOIN gc_zh_chat_log ON gc_zh_chat_log.chat_id=gc_zh_chat.id
            WHERE ( gc_zh_chat.wxapp_id=$wxapp_id  AND  gc_zh_chat.STATUS=1 AND gc_zh_chat.u_id=$uId )
             OR (gc_zh_chat.wxapp_id=$wxapp_id AND  gc_zh_chat.STATUS=1 AND gc_zh_chat.s_id=$uId)";
*/
        //查询接收人是我，发件人不是系统的
        $sql = "SELECT COUNT(c.id)  as num FROM gc_zh_chat c LEFT JOIN gc_zh_chat_log l ON l.chat_id=c.id WHERE c.wxapp_id=$wxapp_id AND c.u_id > 0 AND c.s_id={$uId} AND l.is_read=0 AND c.status=1";

        //查询我收到的未读的私信
        $systemtSql = "SELECT COUNT(c.id)  as num FROM gc_zh_chat c LEFT JOIN gc_zh_chat_log l ON l.chat_id=c.id WHERE c.wxapp_id=$wxapp_id AND c.u_id = 0 AND c.s_id={$uId} AND  l.is_read=0 AND c.status=1";

        $query = Db::connect('mysql');
        $count = $query->query($sql)[0]["num"];
        $systemCount = $query->query($systemtSql)[0]["num"];

        return $this->ajaxReturn($this->successCode, '返回成功', [
            'un_read' => $count,
            'system' => $systemCount
        ]);
    }

    function systemList(){
        $wxapp_id = $this->request->get('wxapp_id');
        $uId      = $this->request->get('uid');
        $op      = $this->request->get('op');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }
        if($op=="test"){
            $uId=380;
        }
        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if (!$user) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }

        $systemtSql = "SELECT c.wxapp_id, c.id, c.s_id, c.status, c.create_time, l.type,l.content,l.record_time,l.is_read ".
            "FROM gc_zh_chat c LEFT JOIN gc_zh_chat_log l ON l.chat_id=c.id ".
            "WHERE c.wxapp_id=$wxapp_id AND c.u_id = 0 AND c.s_id={$uId} AND  l.is_read=0 AND c.status=1".
            " ORDER BY l.id DESC";
        $query = Db::connect('mysql');
        $data = $query->query($systemtSql);
        return $this->ajaxReturn($this->successCode, '成功', $data);
    }


    // 移除会话列表
    function removeChat()
    {
        $wxapp_id = $this->request->post('wxapp_id');
        $uId      = $this->request->uid;
        $chatId   = $this->request->post('chat_id', '', 'serach_in');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if (!$user) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }
        if (!$chatId) {
            return $this->ajaxReturn($this->errorCode, '缺少参数');
        }
        ZhChatModel::where(['wxapp_id' => $wxapp_id, 'id' => $chatId, 'status' => 1])->update(['status' => 0]);
        return $this->ajaxReturn($this->successCode, '成功');
    }
}